#include<iostream>
#include<vector>
#include<queue>
using namespace std;


struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};


vector<vector<int>> levelOrder(TreeNode* root) {
    vector<vector<int>> ans;
    queue<TreeNode*> q;
    if(root != nullptr)
        q.push(root);
    int size = 0;
    while(q.size())
    {
        vector<int> curLevel;
        size = q.size();
        for(int i = 0;i < size;++i){
            if(q.front()->left)
                q.push(q.front()->left);
            if(q.front()->right)
                q.push(q.front()->right);
            curLevel.push_back(q.front()->val);
            q.pop();
        }
        ans.push_back(curLevel);
    }
    return ans;
}
int main()
{
    TreeNode* root = new TreeNode(3);
    TreeNode* cur = root;
    cur->left = new TreeNode(9);
    cur->right = new TreeNode(20);
    cur = cur->right;
    cur->left = new TreeNode(15);
    cur->right = new TreeNode(7);
    vector<vector<int>> ans = levelOrder(root);
    for (auto& v : ans) {
        for (auto& x : v) {
            cout << x << " ";
        }
        cout << endl;
    }
    return 0;
}